from flask import Flask, request, jsonify
from xtquant import xtdata
import time
import logging
from flask_cors import CORS

app = Flask(__name__)

CORS(app, resources={r"/*": {"origins": "*"}})


# 设置日志记录
logging.basicConfig(level=logging.INFO)

# 假设的数据缓存
data_cache = {}

def do_subscribe_quote(stock_list:list, period:str):
  for i in stock_list:
    xtdata.subscribe_quote(i,period = period)
  time.sleep(1) # 等待订阅完成

@app.route('/get_stock_data', methods=['GET'])
def get_stock_data():
    stock_code = request.args.get('code', '000001.SZ')
    period = request.args.get('period', '1d')
    count = request.args.get('count', None)
    start_time = request.args.get('start_time', '')
    end_time = request.args.get('end_time', '')
    p = period
    if period == "15m":
        p = "5m"
    if period == "30m":
        p = "5m"
    if period == "1h":
        p = "5m"
    if period == "2h":
        p = "5m"

    # 尝试将count转换为整数，如果未指定，则保留为None
    if count is not None:
        try:
            count = int(count)
        except ValueError:
            return jsonify({"error": "Invalid 'count' parameter, must be an integer."}), 400
    #do_subscribe_quote([stock_code], p)
    # 下载历史数据，包括指定的时间范围
    xtdata.download_history_data(stock_code, period=p, start_time=start_time, end_time=end_time, incrementally=True)

    # 根据参数获取市场数据
    history_data = xtdata.get_market_data_ex([], [stock_code], period=period,
                                             end_time=end_time, dividend_type="front",
                                             count=count)

    # 将DataFrame转换为JSON格式的字符串
    history_data_json = history_data[stock_code].to_json(orient='records')

    return history_data_json

@app.route('/dates', methods=['GET'])
def get_trading_calendar():
    # 从请求中获取start_time和end_time，如果未提供，则使用默认值

    try:
        # 获取交易日历
        trading_days = xtdata.get_trading_dates("SH", '19910101', '20241231')
        print(trading_days)
        # 将交易日列表转换为JSON格式并返回
        return jsonify(trading_days)
    except Exception as e:
        print(e)
        return jsonify({"error": str(e)}), 500

if __name__ == '__main__':
    # app.run(debug=True, host='0.0.0.0', port=80, use_reloader=True)
    app.run(debug=True, host='0.0.0.0', ssl_context=('cert/stock.deployment.cn_bundle.crt', 'cert/stock.deployment.cn.key'), port=443, use_reloader=True)
